package com.jwsoft.manager.core.integration.individuation.helper;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.jwsoft.manager.common.enums.CardTypeEnum;
import com.jwsoft.manager.common.enums.ComplaintTypeEnum;
import com.jwsoft.manager.common.enums.EnrollStatusFormalEnum;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheVO;
import com.jwsoft.manager.common.vo.eduBreakThrough.EduBreakThroughCreateVO;
import com.jwsoft.manager.common.vo.eduLivePlace.EduLivePlaceVO;
import com.jwsoft.manager.common.vo.eduSchool.SchoolDistrictQueryVO;
import com.jwsoft.manager.common.vo.eduSchool.SchoolDistrictVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollBefore.HouseSchoolVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollBefore.HouseholdSchoolVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduSystemConfigIntegration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 东阳生成预报名工具类
 * **/
@Component
public class DyEnrollBeforeCreateHelper {
    @Autowired
    EduStudentEnrollBeforeService eduStudentEnrollBeforeService;
    @Autowired
    private EduHouseholdService eduHouseholdService;
    @Autowired
    private EduAddressSchoolService eduAddressSchoolService;
    @Autowired
    private EduAddressService eduAddressService;
    @Autowired
    private EduHouseService eduHouseService;
    @Autowired
    private EduUnionSchoolDetailService eduUnionSchoolDetailService;
    @Autowired
    private EduUnionSchoolService eduUnionSchoolService;
    @Autowired
    private EduAppointStudentService eduAppointStudentService;
    @Autowired
    CommonIntegration commonIntegration;
    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    private EduSchoolBbService eduSchoolBbService;
    @Autowired
    private EduStudentEnrollFamilyService eduStudentEnrollFamilyService;
    @Autowired
    private EduSystemConfigIntegration eduSystemConfigIntegration;
    @Autowired
    private EduBreakThroughService eduBreakThroughService;
    @Autowired
    private EduLivePlaceService eduLivePlaceService;
    private final static String areaCode="330783";
    private final static String jthStr = "非亲属,其他非亲属,侄子,外甥女,外甥,侄女,小集体户主,其他";
    private final static String wnczqxlhdz = "和堂村,东联村,东屏村,雅溪村";
    /**
     * 单个预采集数据生成预报名
     * **/
    @Transactional
    public int createEnrollBefore(EduStudentEnrollPre eduStudentEnrollPre){
        String studentEnrollPreId=eduStudentEnrollPre.getStudentEnrollPreId();
        if(StringUtils.isBlank(studentEnrollPreId)){
            throw new AppException("预采集id不能为空");
        }
        if(CardTypeEnum.compatriot.getType().equalsIgnoreCase(eduStudentEnrollPre.getCardType())
                ||CardTypeEnum.passcheck.getType().equalsIgnoreCase(eduStudentEnrollPre.getCardType())
                ||CardTypeEnum.gapermit.getType().equalsIgnoreCase(eduStudentEnrollPre.getCardType())
                ||CardTypeEnum.passport.getType().equalsIgnoreCase(eduStudentEnrollPre.getCardType())
                ||CardTypeEnum.wgridcard.getType().equalsIgnoreCase(eduStudentEnrollPre.getCardType())){
            //港澳台等同于有户籍
            eduStudentEnrollPre.setCanEnroll(BoolEnum.TRUE.getType());
        }else {
            eduStudentEnrollPre.setCanEnroll(BoolEnum.FALSE.getType());
            //判断是否有户籍
            String idcard = eduStudentEnrollPre.getIdcard();
            QueryWrapper<EduHousehold> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduHousehold::getIdcard, idcard)
                    .eq(EduHousehold::getStatus, BoolEnum.TRUE.getType())
                    .eq(EduHousehold::getAuthStatus, AuthStatusEnum.YES.getType())
                    .eq(EduHousehold::getAreaCode, eduStudentEnrollPre.getAreaCode())
                    .eq(EduHousehold::getYear, eduStudentEnrollPre.getYear())
                    .orderByDesc(EduHousehold::getQysj);
            if (eduHouseholdService.count(queryWrapper) > 0) {
                eduStudentEnrollPre.setCanEnroll(BoolEnum.TRUE.getType());
            } else {
                //没有户籍判断居住证
                List<String> idcardList = new ArrayList<>();
                if (StringUtils.isNotBlank(eduStudentEnrollPre.getIdcard())) {
                    idcardList.add(eduStudentEnrollPre.getIdcard());
                }
                if (StringUtils.isNotBlank(eduStudentEnrollPre.getFatherIdcard())) {
                    idcardList.add(eduStudentEnrollPre.getFatherIdcard());
                }
                if (StringUtils.isNotBlank(eduStudentEnrollPre.getMotherIdcard())) {
                    idcardList.add(eduStudentEnrollPre.getMotherIdcard());
                }
                EduOperationCacheQueryVO queryOpVO = new EduOperationCacheQueryVO();
                queryOpVO.setOperating("YW051");
                queryOpVO.setAreaCode(eduStudentEnrollPre.getAreaCode());
                queryOpVO.setClassify("2");
                EduOperationCacheDetailVO jzzOption = eduSystemConfigIntegration.getEduOperationOne(queryOpVO);
                Integer endTime = 0;
                if (jzzOption != null && jzzOption.getEndTime() != null) {
                    endTime = Integer.parseInt(DateUtil.format(jzzOption.getEndTime(), "YYYYMMDD"));
                }
                QueryWrapper<EduLivePlace> livePlaceQueryWrapper = new QueryWrapper<>();
                livePlaceQueryWrapper.lambda().eq(EduLivePlace::getYear, eduStudentEnrollPre.getYear())
                        .eq(EduLivePlace::getAreaCode, eduStudentEnrollPre.getAreaCode())
                        .in(EduLivePlace::getSfzh, idcardList).orderByAsc(EduLivePlace::getSfzh);
                List<EduLivePlace> livePlaceList = eduLivePlaceService.list(livePlaceQueryWrapper);

                if (!CollectionUtils.isEmpty(livePlaceList)) {
                    for (EduLivePlace eduLivePlace : livePlaceList) {
                        boolean jzzFlag = false;
                        if (StringUtils.isNotBlank(eduLivePlace.getQzdqrq()) && endTime != 0) {
                            if (("2".equalsIgnoreCase(eduLivePlace.getZjztdm()) || "3".equalsIgnoreCase(eduLivePlace.getZjztdm()) || "正常".equals(eduLivePlace.getZjzt()))) {
                                String today = DateUtil.today().replaceAll("-", "");
                                //正常和待签注处理
                                if (Integer.parseInt(eduLivePlace.getQzdqrq().replaceAll("-", "").replaceAll("/", "")) <= endTime && Integer.parseInt(today) < endTime) {
                                    jzzFlag = false;
                                } else {
                                    jzzFlag = true;
                                }
                            }
                        } else {
                            if ("正常".equalsIgnoreCase(eduLivePlace.getZjzt())) {
                                jzzFlag = true;
                            } else {
                                jzzFlag = false;
                            }
                        }
                        if (jzzFlag) {
                            eduStudentEnrollPre.setCanEnroll(BoolEnum.TRUE.getType());
                            break;
                        }
                    }

                }
            }
        }
        //判断是否有居住证
        List<String> enrollStatusList=new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        QueryWrapper<EduStudentEnroll> enrollQueryWrapper=new QueryWrapper<>();
        enrollQueryWrapper.lambda().eq(EduStudentEnroll::getIdcard,eduStudentEnrollPre.getIdcard())
                .in(EduStudentEnroll::getEnrollStatus,enrollStatusList)
                .eq(EduStudentEnroll::getYear,eduStudentEnrollPre.getYear());
        if(eduStudentEnrollService.count(enrollQueryWrapper)>0){
            throw new AppException("该学生已报名，不能重复生成");
        }
        //查询是否存在预报名数据,不是特殊人员的可以重新生成，特殊人员只能手动删除
        QueryWrapper<EduStudentEnrollBefore> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().select(EduStudentEnrollBefore::getEnrollBeforeId).eq(EduStudentEnrollBefore::getStudentEnrollPreId,studentEnrollPreId)
                .eq(EduStudentEnrollBefore::getSpecialFlag, BoolEnum.FALSE.getType());
        List<EduStudentEnrollBefore> oldBeforeList=eduStudentEnrollBeforeService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(oldBeforeList)){
            List<Long> oldIdList=oldBeforeList.stream().map(EduStudentEnrollBefore::getEnrollBeforeId).collect(Collectors.toList());
            eduStudentEnrollBeforeService.removeByIds(oldIdList);
        }
        //获取招生年度
        int year=eduStudentEnrollPre.getYear();
        //获取招生配置参数
        EduOperationCacheQueryVO queryVO=new EduOperationCacheQueryVO();
        queryVO.setClassify("2");
        queryVO.setAreaCode(areaCode);
        queryVO.setYear(year);
        EduOperationCacheVO eduOperationCacheVO=eduSystemConfigIntegration.getEduOperation(queryVO);
        if(eduOperationCacheVO==null){
            throw new AppException("本年度义务教育阶段招生参数未配置，请联系系统管理员");
        }
        Map<String, EduOperationCacheDetailVO> operation=eduOperationCacheVO.getOperation();
        EduOperationCacheDetailVO fcOperation=operation.get("YW024");
        if(fcOperation==null||fcOperation.getEndTime()==null){
            throw new AppException(year+"年度义务教育阶段招生参数未配置房产有效截止时间");
        }
        EduOperationCacheDetailVO hjOperation=operation.get("YW025");
        if(hjOperation==null||hjOperation.getEndTime()==null){
            throw new AppException(year+"年度义务教育阶段招生参数未配置户籍有效截止时间");
        }
        List<EduStudentEnrollBefore> list=compare(eduStudentEnrollPre,operation);
        //判断是否补报，补报需要清除,只要过了家长报名时间，就按补报处理
        long curTime = DateUtil.currentSeconds();
        EduOperationCacheDetailVO bmOperation=operation.get("YW002");

        if(bmOperation!=null&&bmOperation.getEndTime()!=null){
            Date applyEndDate=bmOperation.getEndTime();
            if(applyEndDate.getTime()/1000-curTime<0){
                QueryWrapper<EduSchoolBb> bbQueryWrapper=new QueryWrapper<>();
                bbQueryWrapper.lambda().select(EduSchoolBb::getSchoolId).eq(EduSchoolBb::getYear,eduStudentEnrollPre.getYear())
                .eq(EduSchoolBb::getAreaCode,areaCode);
                List<EduSchoolBb> bbList=eduSchoolBbService.list(bbQueryWrapper);
                if(!CollectionUtils.isEmpty(bbList)){
                    List<String> schoolList=bbList.stream().map(EduSchoolBb::getSchoolId).distinct().collect(Collectors.toList());
                    List<EduStudentEnrollBefore> retList=new ArrayList<>();
                    for(EduStudentEnrollBefore before:list){
                        if(schoolList.contains(before.getSchoolId())){
                            before.setAreaCode(areaCode);
                            retList.add(before);
                        }
                    }
                    list=retList;
                }else{
                    return 0;
                }
            }
        }
        if(!CollectionUtils.isEmpty(list)){
            eduStudentEnrollBeforeService.saveBatch(list);
            return list.size();
        }
        return 0;
    }
    //比对
    private List<EduStudentEnrollBefore> compare(EduStudentEnrollPre eduStudentEnrollPre, Map<String, EduOperationCacheDetailVO> operation){
        List<EduStudentEnrollBefore> list=new ArrayList<>();
        //获取房产学校
        List<HouseSchoolVO> houseSchoolVOList=this.getHouseSchool(eduStudentEnrollPre,operation);
        //获取户籍学校
        List<HouseholdSchoolVO> householdSchoolVOList=this.getHouseholdSchool(eduStudentEnrollPre,operation);
        //处理户籍跨区域联合数据
        //就高集合
        List<Map<String,String>> jgList=new ArrayList<>();
        List<String> jthList = Arrays.stream(jthStr.split(",")).map(s -> s).collect(Collectors.toList());
        //处理户籍联合区后的数据
        List<String> czwnqxlhqList = Arrays.stream(wnczqxlhdz.split(",")).map(s -> s).collect(Collectors.toList());
        List<HouseholdSchoolVO> householdSchoolList=new ArrayList<>();
        if(!CollectionUtils.isEmpty(householdSchoolVOList)){
            for(HouseholdSchoolVO householdSchoolVO:householdSchoolVOList){
                if("集体户".equalsIgnoreCase(householdSchoolVO.getAccountType())
                        ||(StringUtils.isNotBlank(householdSchoolVO.getRelation())
                        && jthList.contains(householdSchoolVO.getRelation()))) {
                    //如果是集体户或者挂靠户 不做联合区比对
                    continue;
                }
                if(SchoolCategoryEnum.JUNIOR.getType().equalsIgnoreCase(eduStudentEnrollPre.getSchoolCategory())){
                    //目前初中只有吴宁区块，需要过滤城东街道的相关村不能使用联合区
                    if(!CollectionUtils.isEmpty(czwnqxlhqList)){
                        boolean cdjdFlag=false;
                        for(String wnqk:czwnqxlhqList){
                            if(householdSchoolVO.getAddress().indexOf(wnqk)>=0){
                                cdjdFlag=true;
                                break;
                            }
                        }
                        if (cdjdFlag){
                            continue;
                        }
                    }
                }
                QueryWrapper<EduUnionSchoolDetail> unionSchoolDetailQueryWrapper=new QueryWrapper<>();
                unionSchoolDetailQueryWrapper.lambda().eq(EduUnionSchoolDetail::getSchoolId,householdSchoolVO.getSchoolId())
                        .eq(EduUnionSchoolDetail::getStatus,BoolEnum.TRUE.getType())
                        .eq(EduUnionSchoolDetail::getYear,eduStudentEnrollPre.getYear());
                List<EduUnionSchoolDetail> schoolDetailList=eduUnionSchoolDetailService.list(unionSchoolDetailQueryWrapper);
                if(!CollectionUtils.isEmpty(schoolDetailList)){
                    if(schoolDetailList.size()>1){
                        throw new AppException("学校("+householdSchoolVO.getSchoolId()+")存在多个户籍联合区，请核对数据");
                    }
                    EduUnionSchoolDetail eduUnionSchoolDetail=schoolDetailList.get(0);
                    QueryWrapper<EduUnionSchool> eduUnionSchoolQueryWrapper=new QueryWrapper<>();
                    eduUnionSchoolQueryWrapper.lambda().eq(EduUnionSchool::getYear,eduStudentEnrollPre.getYear())
                        .eq(EduUnionSchool::getUnionSchoolId,eduUnionSchoolDetail.getUnionSchoolId());
                    EduUnionSchool eduUnionSchool=eduUnionSchoolService.getOne(eduUnionSchoolQueryWrapper);
                    if(eduUnionSchool==null){
                        continue;
                    }
                    QueryWrapper<EduUnionSchoolDetail> detailQueryWrapper=new QueryWrapper<>();
                    detailQueryWrapper.lambda().eq(EduUnionSchoolDetail::getUnionSchoolId,eduUnionSchool.getUnionSchoolId())
                            .eq(EduUnionSchoolDetail::getStatus,BoolEnum.TRUE.getType())
                            .eq(EduUnionSchoolDetail::getYear,eduStudentEnrollPre.getYear());
                    List<EduUnionSchoolDetail> detailList=eduUnionSchoolDetailService.list(detailQueryWrapper);
                    if (!CollectionUtils.isEmpty(detailList)){
                        Map<String,String> jgMap=new HashMap<>();
                        for(EduUnionSchoolDetail detail:detailList){
                            HouseholdSchoolVO schoolVO=new HouseholdSchoolVO();
                            BeanUtil.copyProperties(householdSchoolVO,schoolVO);
                            schoolVO.setSchoolId(detail.getSchoolId());
                            householdSchoolList.add(schoolVO);
                            jgMap.put(detail.getSchoolId(),detail.getSchoolId());

                        }
                        if(BoolEnum.TRUE.getType().equals(eduUnionSchool.getHighFlag())){
                            jgList.add(jgMap);
                        }
                    }

                }
            }
        }

        Map<String,String> schoolMap=new HashMap<>();
        Map<String,String> houseMap=new HashMap<>();
        //生成学校ABC类别
        //户籍联合区 只处理有房产的数据
        for(HouseholdSchoolVO householdSchoolVO:householdSchoolList){

            //判断是否有房产，有的话升到A
            for(HouseSchoolVO houseSchoolVO:houseSchoolVOList){
                if(houseSchoolVO.getSchoolId().equals(householdSchoolVO.getSchoolId())){
                    EduStudentEnrollBefore eduStudentEnrollBefore=new EduStudentEnrollBefore();
                    eduStudentEnrollBefore.setHouseholdId(householdSchoolVO.getHouseholdId());
                    eduStudentEnrollBefore.setHouseholdAdress(householdSchoolVO.getAddress());
                    eduStudentEnrollBefore.setAuthStatus(AuthStatusEnum.YES.getType());
                    eduStudentEnrollBefore.setAuthRemarks("系统大数据比对,户籍联合区");
                    eduStudentEnrollBefore.setCreateName("东阳新生报名系统");
                    eduStudentEnrollBefore.setAreaCode(areaCode);
                    eduStudentEnrollBefore.setSchoolId(householdSchoolVO.getSchoolId());
                    eduStudentEnrollBefore.setYear(eduStudentEnrollPre.getYear());
                    eduStudentEnrollBefore.setStudentEnrollPreId(eduStudentEnrollPre.getStudentEnrollPreId());
                    eduStudentEnrollBefore.setConfigName("B");//有户籍默认是B
                    eduStudentEnrollBefore.setPrivateAppointFlag(BoolEnum.FALSE.getType());
                    eduStudentEnrollBefore.setAppointFlag(BoolEnum.FALSE.getType());
                    eduStudentEnrollBefore.setSpecialFlag(BoolEnum.FALSE.getType());
                    eduStudentEnrollBefore.setConfigName("A");//有房有户升级到A
                    eduStudentEnrollBefore.setHouseId(houseSchoolVO.getHouseId());
                    eduStudentEnrollBefore.setHouseAdreess(houseSchoolVO.getAddress());
                    if(!schoolMap.containsKey(householdSchoolVO.getSchoolId())){
                        schoolMap.put(householdSchoolVO.getSchoolId(),eduStudentEnrollBefore.getConfigName());
                        houseMap.put(houseSchoolVO.getHouseId(),houseSchoolVO.getRealProperty());
                        list.add(eduStudentEnrollBefore);
                    }else {
                        if(schoolMap.get(householdSchoolVO.getSchoolId()).equals(eduStudentEnrollBefore.getConfigName())
                                &&!houseMap.containsKey(houseSchoolVO.getHouseId())&&!houseMap.containsValue(houseSchoolVO.getRealProperty())){
                            houseMap.put(houseSchoolVO.getHouseId(),houseSchoolVO.getRealProperty());
                            list.add(eduStudentEnrollBefore);
                        }
                    }
                }
            }


        }
        //有户及有户有房
        for(HouseholdSchoolVO householdSchoolVO:householdSchoolVOList){

            EduStudentEnrollBefore eduStudentEnrollBefore=new EduStudentEnrollBefore();
            eduStudentEnrollBefore.setHouseholdId(householdSchoolVO.getHouseholdId());
            eduStudentEnrollBefore.setHouseholdAdress(householdSchoolVO.getAddress());
            eduStudentEnrollBefore.setAuthStatus(AuthStatusEnum.YES.getType());
            eduStudentEnrollBefore.setAuthRemarks("系统大数据比对，学校关联的户籍");
            eduStudentEnrollBefore.setCreateName("东阳新生报名系统");
            eduStudentEnrollBefore.setAreaCode(areaCode);
            eduStudentEnrollBefore.setSchoolId(householdSchoolVO.getSchoolId());
            eduStudentEnrollBefore.setYear(eduStudentEnrollPre.getYear());
            eduStudentEnrollBefore.setStudentEnrollPreId(eduStudentEnrollPre.getStudentEnrollPreId());
            eduStudentEnrollBefore.setConfigName("B");//有户籍默认是B
            if("集体户".equalsIgnoreCase(householdSchoolVO.getAccountType())
                    ||(StringUtils.isNotBlank(householdSchoolVO.getRelation())
                    && jthList.contains(householdSchoolVO.getRelation()))) {
                //如果是集体户或者挂靠户
                eduStudentEnrollBefore.setConfigName("特殊户口");
                eduStudentEnrollBefore.setAuthRemarks("系统大数据比对，集体户或挂靠户");
            }
            eduStudentEnrollBefore.setPrivateAppointFlag(BoolEnum.FALSE.getType());
            eduStudentEnrollBefore.setAppointFlag(BoolEnum.FALSE.getType());
            eduStudentEnrollBefore.setSpecialFlag(BoolEnum.FALSE.getType());
            //判断是否有房产，有的话升到A
            boolean flag=true;
            for(HouseSchoolVO houseSchoolVO:houseSchoolVOList){
                if(houseSchoolVO.getSchoolId().equals(householdSchoolVO.getSchoolId())){
                    EduStudentEnrollBefore aBefore=new EduStudentEnrollBefore();
                    BeanUtil.copyProperties(eduStudentEnrollBefore,aBefore);
                    if(eduStudentEnrollBefore.getConfigName().equalsIgnoreCase("B")){
                        //正常户口
                        aBefore.setConfigName("A");//有房有户升级到A
                    }else{
                        aBefore.setConfigName("C");//特殊户口按房产处理升到C
                    }

                    aBefore.setHouseId(houseSchoolVO.getHouseId());
                    aBefore.setHouseAdreess(houseSchoolVO.getAddress());
                    if(!schoolMap.containsKey(householdSchoolVO.getSchoolId())){
                        schoolMap.put(householdSchoolVO.getSchoolId(),aBefore.getConfigName());
                        houseMap.put(houseSchoolVO.getHouseId(),houseSchoolVO.getRealProperty());
                        list.add(aBefore);
                    }else {
                        if(schoolMap.get(householdSchoolVO.getSchoolId()).equals(aBefore.getConfigName())
                                &&!houseMap.containsKey(houseSchoolVO.getHouseId())&&!houseMap.containsValue(houseSchoolVO.getRealProperty())){
                            houseMap.put(houseSchoolVO.getHouseId(),houseSchoolVO.getRealProperty());
                            list.add(aBefore);
                        }
                    }
                    flag=false;

                }
            }
            if(flag){
                schoolMap.put(householdSchoolVO.getSchoolId(),eduStudentEnrollBefore.getConfigName());
                list.add(eduStudentEnrollBefore);
            }
        }
        //有房
        for(HouseSchoolVO houseSchoolVO:houseSchoolVOList){
            //判断是否存在
            EduStudentEnrollBefore eduStudentEnrollBefore=new EduStudentEnrollBefore();
            eduStudentEnrollBefore.setHouseId(houseSchoolVO.getHouseId());
            eduStudentEnrollBefore.setHouseAdreess(houseSchoolVO.getAddress());
            eduStudentEnrollBefore.setAuthStatus(AuthStatusEnum.YES.getType());
            eduStudentEnrollBefore.setAuthRemarks("系统大数据比对，学校关联的房产");
            eduStudentEnrollBefore.setCreateName("东阳新生报名系统");
            eduStudentEnrollBefore.setAreaCode(areaCode);
            eduStudentEnrollBefore.setSchoolId(houseSchoolVO.getSchoolId());
            eduStudentEnrollBefore.setYear(eduStudentEnrollPre.getYear());
            eduStudentEnrollBefore.setStudentEnrollPreId(eduStudentEnrollPre.getStudentEnrollPreId());
            eduStudentEnrollBefore.setConfigName("C");//只有房默认是C
            eduStudentEnrollBefore.setPrivateAppointFlag(BoolEnum.FALSE.getType());
            eduStudentEnrollBefore.setAppointFlag(BoolEnum.FALSE.getType());
            eduStudentEnrollBefore.setSpecialFlag(BoolEnum.FALSE.getType());
            if(!schoolMap.containsKey(houseSchoolVO.getSchoolId())){
                schoolMap.put(eduStudentEnrollBefore.getSchoolId(),eduStudentEnrollBefore.getConfigName());
                houseMap.put(houseSchoolVO.getHouseId(),houseSchoolVO.getRealProperty());
                list.add(eduStudentEnrollBefore);
            }else {
                if(schoolMap.get(houseSchoolVO.getSchoolId()).equals(eduStudentEnrollBefore.getConfigName())
                        &&!houseMap.containsKey(houseSchoolVO.getHouseId())&&!houseMap.containsValue(houseSchoolVO.getRealProperty())){
                    houseMap.put(houseSchoolVO.getHouseId(),houseSchoolVO.getRealProperty());
                    list.add(eduStudentEnrollBefore);
                }
            }
        }
        if(!CollectionUtils.isEmpty(list)){
            //户籍跨区联合就高处理
            if(!CollectionUtils.isEmpty(jgList)){

                for(Map<String,String> jgMap:jgList){
                    //获取本联合区最高类别
                    String configName="C";
                    int max=4;
                    for(String schoolId:jgMap.keySet()){
                        String thisConfigName= schoolMap.get(schoolId);
                        int thisIndex=4;
                        if(StringUtils.isNotBlank(thisConfigName)){
                            if(thisConfigName.equalsIgnoreCase("特殊户口")){
                                thisIndex=4;
                            }else if(thisConfigName.equalsIgnoreCase("A")){
                                thisIndex=1;
                            }else if(thisConfigName.equalsIgnoreCase("B")){
                                thisIndex=2;
                            }else if(thisConfigName.equalsIgnoreCase("C")){
                                thisIndex=3;
                            }
                            if(max>=thisIndex){
                                configName=thisConfigName;
                                max=thisIndex;
                            }
                        }
                    }
                    List<EduStudentEnrollBefore> filterList=new ArrayList<>();
                    for(EduStudentEnrollBefore before:list){
                        if(jgMap.containsKey(before.getSchoolId())){
                            if(configName.compareTo(before.getConfigName())==0){
                                filterList.add(before);
                            }
                        }else{
                            filterList.add(before);
                        }
                    }
                    list = filterList;
                }
            }
        }

        //获取城区E
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("cq_school_e");
        commonVO.setAreaCode(areaCode);
        String schoolStr = commonIntegration.getValueByKeyAndArea(commonVO);
        List<String> eSchoolList=new ArrayList<>();
        if(StringUtils.isNotBlank(schoolStr)){
            eSchoolList=Arrays.stream(schoolStr.split(",")).map(s -> s).collect(Collectors.toList());
        }

        Map<String,String> eSchoolIdMap=getAppointSchool(eduStudentEnrollPre);
        if(!CollectionUtils.isEmpty(eSchoolIdMap)){
            for(String eSchoolId: eSchoolIdMap.keySet()){
                boolean flag=true;
                boolean inEschool=eSchoolList.contains(eSchoolId);
                if(!CollectionUtils.isEmpty(list)){
                    for(EduStudentEnrollBefore before:list){
                        if(eSchoolId.equals(before.getSchoolId())){
                            before.setAppointFlag(BoolEnum.TRUE.getType());
                            before.setAppointStudentId(eSchoolIdMap.get(eSchoolId));
                            flag=false;
                            break;
                        }else {
                            if (inEschool) {
                                if(eSchoolList.contains(before.getSchoolId())&&!before.getConfigName().equals("E")){
                                    flag=false;
                                    break;
                                }
                            }
                        }

                    }
                }
                if(flag){
                    EduStudentEnrollBefore eduStudentEnrollBefore=new EduStudentEnrollBefore();
                    eduStudentEnrollBefore.setAuthStatus(AuthStatusEnum.YES.getType());
                    eduStudentEnrollBefore.setAuthRemarks("系统大数据比对");
                    eduStudentEnrollBefore.setAreaCode(areaCode);
                    eduStudentEnrollBefore.setCreateName("东阳新生报名系统");
                    eduStudentEnrollBefore.setSchoolId(eSchoolId);
                    eduStudentEnrollBefore.setYear(eduStudentEnrollPre.getYear());
                    eduStudentEnrollBefore.setStudentEnrollPreId(eduStudentEnrollPre.getStudentEnrollPreId());
                    eduStudentEnrollBefore.setConfigName("E");//只有城区E
                    eduStudentEnrollBefore.setPrivateAppointFlag(BoolEnum.FALSE.getType());
                    eduStudentEnrollBefore.setAppointFlag(BoolEnum.TRUE.getType());
                    eduStudentEnrollBefore.setAppointStudentId(eSchoolIdMap.get(eSchoolId));
                    eduStudentEnrollBefore.setSpecialFlag(BoolEnum.FALSE.getType());
                    list.add(eduStudentEnrollBefore);
                }

            }
        }
        //突破学区处理
        List<EduStudentEnrollBefore> breakBeforeList = new ArrayList<>();
        for (EduStudentEnrollBefore before : list) {
            List<EduBreakThroughCreateVO> breakThroughCreateVOS = eduBreakThroughService.getMainSchoolBySchoolId(before.getSchoolId(), before.getYear());
            if (!CollectionUtils.isEmpty(breakThroughCreateVOS)) {
                for (EduBreakThroughCreateVO breakThroughCreateVO : breakThroughCreateVOS) {
                    if (StringUtils.isBlank(breakThroughCreateVO.getConfigNameList())) {
                        continue;
                    }
                    List<String> configNameList = Arrays.stream(breakThroughCreateVO.getConfigNameList().split(",")).map(s -> s).collect(Collectors.toList());
                    if (configNameList.contains(before.getConfigName())) {
                        EduStudentEnrollBefore eduStudentEnrollBefore = new EduStudentEnrollBefore();
                        BeanUtil.copyProperties(before, eduStudentEnrollBefore);
                        eduStudentEnrollBefore.setSchoolId(breakThroughCreateVO.getSchoolId());
                        eduStudentEnrollBefore.setAuthRemarks("系统设置，突破学区");
                        boolean befaddFlag=true;
                        for(EduStudentEnrollBefore addBefore:list){
                            if(eduStudentEnrollBefore.getSchoolId().equalsIgnoreCase(addBefore.getSchoolId())&&!"E".equalsIgnoreCase(addBefore.getConfigName())){
                                if ("A".equals(eduStudentEnrollBefore.getConfigName())&&"A".equals(addBefore.getConfigName())){
                                    if (eduStudentEnrollBefore.getHouseholdId().equals(addBefore.getHouseholdId())&&eduStudentEnrollBefore.getHouseId().equals(addBefore.getHouseId())){
                                        //如果本学区内已经匹配的学校，并且不是城区E，不再突破
                                        befaddFlag=false;
                                        break;
                                    }
                                }else if ("B".equals(eduStudentEnrollBefore.getConfigName())&&"B".equals(addBefore.getConfigName())){
                                    if (eduStudentEnrollBefore.getHouseholdId().equals(addBefore.getHouseholdId())){
                                        //如果本学区内已经匹配的学校，并且不是城区E，不再突破
                                        befaddFlag=false;
                                        break;
                                    }
                                }else if ("C".equals(eduStudentEnrollBefore.getConfigName())&&"C".equals(addBefore.getConfigName())){
                                    if (eduStudentEnrollBefore.getHouseId().equals(addBefore.getHouseId())){
                                        //如果本学区内已经匹配的学校，并且不是城区E，不再突破
                                        befaddFlag=false;
                                        break;
                                    }
                                }else if ("特殊户口".equals(eduStudentEnrollBefore.getConfigName())&&"特殊户口".equals(addBefore.getConfigName())){
                                    if (eduStudentEnrollBefore.getHouseholdId().equals(addBefore.getHouseholdId())){
                                        //如果本学区内已经匹配的学校，并且不是城区E，不再突破
                                        befaddFlag=false;
                                        break;
                                    }
                                }



                            }
                        }
                        if(befaddFlag) {
                            boolean hasFlag=false;
                            for (EduStudentEnrollBefore addBefore:breakBeforeList){
                                if(eduStudentEnrollBefore.getSchoolId().equalsIgnoreCase(addBefore.getSchoolId())){
                                    if ("A".equals(eduStudentEnrollBefore.getConfigName())&&"A".equals(addBefore.getConfigName())){
                                        if (eduStudentEnrollBefore.getHouseholdId().equals(addBefore.getHouseholdId())&&eduStudentEnrollBefore.getHouseId().equals(addBefore.getHouseId())){
                                            hasFlag=true;
                                            break;
                                        }
                                    }else if ("B".equals(eduStudentEnrollBefore.getConfigName())&&"B".equals(addBefore.getConfigName())){
                                        if (eduStudentEnrollBefore.getHouseholdId().equals(addBefore.getHouseholdId())){
                                            hasFlag=true;
                                            break;
                                        }
                                    }else if ("C".equals(eduStudentEnrollBefore.getConfigName())&&"C".equals(addBefore.getConfigName())){
                                        if (eduStudentEnrollBefore.getHouseId().equals(addBefore.getHouseId())){
                                            hasFlag=true;
                                            break;
                                        }
                                    }else if ("特殊户口".equals(eduStudentEnrollBefore.getConfigName())&&"特殊户口".equals(addBefore.getConfigName())){
                                        if (eduStudentEnrollBefore.getHouseholdId().equals(addBefore.getHouseholdId())){
                                            hasFlag=true;
                                            break;
                                        }
                                    }else if("E".equals(eduStudentEnrollBefore.getConfigName())&&"E".equalsIgnoreCase(addBefore.getConfigName())){
                                        hasFlag=true;
                                        break;
                                    }



                                }
                            }
                            if (!hasFlag) {
                                breakBeforeList.add(eduStudentEnrollBefore);
                            }
                        }
                    }

                }
            }
        }
        list.addAll(breakBeforeList);
        return list;
    }
    //获取房产信息所属学校
    public List<HouseSchoolVO> getHouseSchool(EduStudentEnrollPre eduStudentEnrollPre, Map<String, EduOperationCacheDetailVO> operation){
        List<HouseSchoolVO> retList=new ArrayList<>();
        //获取本人以及父母名下房产信息
        List<String> idcardList=new ArrayList<>();
        if(StringUtils.isNotBlank(eduStudentEnrollPre.getIdcard())){
            idcardList.add(eduStudentEnrollPre.getIdcard());
        }
        LambdaQueryWrapper<EduStudentEnrollFamily> familyLambdaQueryWrapper=new LambdaQueryWrapper<>();
        familyLambdaQueryWrapper.select(EduStudentEnrollFamily::getStudentPreFamilyId,EduStudentEnrollFamily::getCardType,EduStudentEnrollFamily::getIdcard).eq(EduStudentEnrollFamily::getStudentEnrollPreId,eduStudentEnrollPre.getStudentEnrollPreId())
                .eq(EduStudentEnrollFamily::getHouseFlag,BoolEnum.TRUE.getType());
        List<EduStudentEnrollFamily> familyList=eduStudentEnrollFamilyService.list(familyLambdaQueryWrapper);
        if(!CollectionUtils.isEmpty(familyList)){
            for(EduStudentEnrollFamily family:familyList){
                if(family!=null&&StringUtils.isNotBlank(family.getIdcard())){
                    idcardList.add(family.getIdcard());
                }

            }
        }

        List<EduHouse> list= eduHouseService.getHouseByAllIdcard(idcardList,eduStudentEnrollPre.getYear());
        if (!CollectionUtils.isEmpty(list)){
            // 户籍启用是参数
            EduOperationCacheDetailVO fcOperation=operation.get("YW024");
            if(fcOperation.getEndTime()==null){
                throw new AppException("房产截止时间未设置");
            }

            Long houseEndTime=Long.parseLong(DateUtil.format(fcOperation.getEndTime(),"yyyyMMdd"));
            for(EduHouse eduHouse:list){
                if(BoolEnum.TRUE.getType().equals(eduHouse.getUseFlag())){
                    //3年内房产使用，不能就读
                    continue;
                }
                //获取房产地址关联的学校信息
                Boolean flag = true;
                String addressId=eduHouse.getAddressId();
                String address= Convert.toDBC(eduHouse.getAddress());
                if(StringUtils.isNotBlank(eduHouse.getAddressId())) {
                    EduAddress eduAddress = eduAddressService.getById(addressId);
                    if (eduAddress == null) {
                        flag = true;
                        addressId = "";
                    } else {
                        if (!eduAddress.getAddressName().equals(address)) {
                            flag = true;
                            addressId = "";
                        } else {
                            flag = false;

                        }
                    }
                }
                if (flag) {
                    QueryWrapper<EduAddress> eduAddressQueryWrapper = new QueryWrapper<>();
                    eduAddressQueryWrapper.lambda().eq(EduAddress::getAddressName, address);
                    List<EduAddress> addressList = eduAddressService.list(eduAddressQueryWrapper);
                    if (CollectionUtils.isEmpty(addressList)) {
                        throw new AppException("地址池中未找到该房产地址，请先联系管理员添加");
                    } else {
                        if (addressList.size() > 1) {
                            throw new AppException("同一房产地址在地址池中找到多条数据，请联系管理员处理");
                        }
                        addressId = addressList.get(0).getAddressId();
                    }
                }

                SchoolDistrictQueryVO queryVO=new SchoolDistrictQueryVO();
                queryVO.setSchoolCategory(eduStudentEnrollPre.getSchoolCategory());
                queryVO.setAddressId(addressId);
                List<SchoolDistrictVO> schoolList= eduAddressSchoolService.getSchoolInfo(queryVO);
                if (!CollectionUtils.isEmpty(schoolList)){
                    for(SchoolDistrictVO eduAddressSchool:schoolList){
                        boolean conFlag = false;
                        for (HouseSchoolVO houseSchoolVO : retList) {
                            if (eduAddressSchool.getAddressId().equalsIgnoreCase(houseSchoolVO.getAddressId()) && houseSchoolVO.getSchoolId().equalsIgnoreCase(eduAddressSchool.getOrgId())) {
                                conFlag = true;
                            }
                        }
                        if (conFlag) {
                            continue;
                        }
                        //判断启用时间是否小于参数设置时间
                        boolean addFlag=true;
                        if(!BoolEnum.TRUE.getType().equals(eduAddressSchool.getHouseEndTimeNo())&&eduHouse.getRegisterDate()!=null){
                            Long djTime=Long.parseLong(DateUtil.format(eduHouse.getRegisterDate(),"yyyyMMdd"));
                            if(eduAddressSchool.getHouseEndTime()!=null){
                                Long endTime=Long.parseLong(DateUtil.format(eduAddressSchool.getHouseEndTime(),"yyyyMMdd"));
                                if(djTime>endTime){
                                    addFlag=false;
                                }
                            }else{
                                if(djTime>houseEndTime){
                                    addFlag=false;
                                }
                            }
                        }

                        if(addFlag) {
                            HouseSchoolVO vo = Convert.convert(HouseSchoolVO.class, eduHouse);
                            vo.setSchoolId(eduAddressSchool.getOrgId());
                            retList.add(vo);
                        }
                    }
                }
            }
        }

        return retList;
    }
    //获取户籍信息所属学校
    public List<HouseholdSchoolVO> getHouseholdSchool(EduStudentEnrollPre eduStudentEnrollPre, Map<String, EduOperationCacheDetailVO> operation){
        String idcard=eduStudentEnrollPre.getIdcard();
        QueryWrapper<EduHousehold> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduHousehold::getIdcard,idcard)
            .eq(EduHousehold::getStatus,BoolEnum.TRUE.getType())
            .eq(EduHousehold::getAuthStatus, AuthStatusEnum.YES.getType())
            .eq(EduHousehold::getYear, eduStudentEnrollPre.getYear()).eq(EduHousehold::getAreaCode,areaCode)
            .orderByDesc(EduHousehold::getQysj);
        List<EduHousehold> list =eduHouseholdService.list(queryWrapper);
        List<HouseholdSchoolVO> retList=new ArrayList<>();
        eduStudentEnrollPre.setFollowingFlag(BoolEnum.FALSE.getType());
        if (!CollectionUtils.isEmpty(list)){
            eduStudentEnrollPre.setFollowingFlag(BoolEnum.TRUE.getType());
            // 户籍启用是参数
            EduOperationCacheDetailVO hjOperation=operation.get("YW025");
            if(hjOperation.getEndTime()==null){
                throw new AppException("YW025户籍截止时间未设置");
            }
            Long householdEndTime=Long.parseLong(DateUtil.format(hjOperation.getEndTime(),"yyyyMMdd"));

            for(EduHousehold eduHousehold:list){
                //获取地址和学校关联关系信息
                Boolean flag = true;
                String addressId=eduHousehold.getAddressId();
                String address= Convert.toDBC(eduHousehold.getAddress());
                if(StringUtils.isNotBlank(addressId)){
                    EduAddress eduAddress=eduAddressService.getById(addressId);
                    if(eduAddress==null){
                        flag=true;
                        addressId="";
                    }else {
                        if (!eduAddress.getAddressName().equals(address)) {
                            flag = true;
                            addressId = "";
                        } else {
                            flag = false;

                        }
                    }
                }
                if(flag){
                    QueryWrapper<EduAddress> eduAddressQueryWrapper=new QueryWrapper<>();
                    eduAddressQueryWrapper.lambda().eq(EduAddress::getAddressName,address);
                    List<EduAddress> addressList=eduAddressService.list(eduAddressQueryWrapper);
                    if(CollectionUtils.isEmpty(addressList)){
                        throw new AppException("地址池中未找到该户籍地址，请先联系管理员添加");
                    }else{
                        if(addressList.size()>1){
                            throw new AppException("同一户籍地址在地址池中找到多条数据，请联系管理员处理");
                        }
                        addressId=addressList.get(0).getAddressId();
                    }
                }
                SchoolDistrictQueryVO queryVO=new SchoolDistrictQueryVO();
                queryVO.setAddressId(addressId);
                queryVO.setSchoolCategory(eduStudentEnrollPre.getSchoolCategory());
                List<SchoolDistrictVO> schoolList= eduAddressSchoolService.getSchoolInfo(queryVO);

                if (!CollectionUtils.isEmpty(schoolList)){
                    for(SchoolDistrictVO eduAddressSchool:schoolList){
                        boolean conFlag = false;
                        for (HouseholdSchoolVO householdSchoolVO : retList) {
                            if (eduAddressSchool.getAddressId().equalsIgnoreCase(householdSchoolVO.getAddressId()) && householdSchoolVO.getSchoolId().equalsIgnoreCase(eduAddressSchool.getOrgId())) {
                                conFlag = true;
                            }
                        }
                        if (conFlag) {
                            continue;
                        }
                        //判断启用时间是否小于参数设置时间
                        boolean addFlag = true;
                        if(!BoolEnum.TRUE.getType().equals(eduAddressSchool.getHouseholdEndTimeNo()) ){
                            if (StringUtils.isNotBlank(eduHousehold.getQysj())) {
                                Long qysj = Long.parseLong(DateUtil.format(DateUtil.parse(eduHousehold.getQysj()), "yyyyMMdd"));
                                if(eduAddressSchool.getHouseholdEndTime()!=null){

                                    Long endTime=Long.parseLong(DateUtil.format(eduAddressSchool.getHouseholdEndTime(),"yyyyMMdd"));
                                    if(qysj>endTime){
                                        addFlag=false;
                                    }
                                }else{
                                    if(qysj>householdEndTime){
                                        addFlag=false;
                                    }
                                }
                            }

                        }
                        if(addFlag){
                            HouseholdSchoolVO vo= Convert.convert(HouseholdSchoolVO.class,eduHousehold);
                            vo.setSchoolId(eduAddressSchool.getOrgId());

                            retList.add(vo);
                        }

                    }
                }
                break;
            }
        }
        return  retList;
    }

    //获取城区E
    private Map<String,String> getAppointSchool(EduStudentEnrollPre eduStudentEnrollPre){
        QueryWrapper<EduAppointStudent> appointStudentQueryWrapper=new QueryWrapper<>();
        appointStudentQueryWrapper.lambda().eq(EduAppointStudent::getYear,eduStudentEnrollPre.getYear())
                .eq(EduAppointStudent::getStatus, BoolEnum.TRUE.getType())
                .eq(EduAppointStudent::getIdcard,eduStudentEnrollPre.getIdcard());
        List<EduAppointStudent> eduAppointStudentList=eduAppointStudentService.list(appointStudentQueryWrapper);
        if(!CollectionUtils.isEmpty(eduAppointStudentList)){
            return eduAppointStudentList.stream().collect(Collectors.toMap(EduAppointStudent::getSchoolId, EduAppointStudent::getAppointStudentId,(k1,k2)->k1));
        }else{
            return null;
        }
    }
}
